package models

import (
	"time"

	"gorm.io/gorm"
)

// Room 房间模型
type Room struct {
	gorm.Model
	Name        string     `json:"name" gorm:"size:100;not null"`
	CreatorID   int        `json:"creator_id" gorm:"not null"`
	CreatorName string     `json:"creator_name" gorm:"size:50"`
	Tag         string     `json:"tag" gorm:"size:20"`
	Password    string     `json:"password" gorm:"size:100"`
	Description string     `json:"description" gorm:"type:text"`
	MaxUsers    int        `json:"max_users" gorm:"default:2"`
	Timeout     int        `json:"timeout"` // 超时时间（分钟）
	IsPlaying   bool       `json:"is_playing" gorm:"default:false"`
	EmptySince  *time.Time `json:"empty_since"`
}

// RoomUser 房间用户关联表
type RoomUser struct {
	gorm.Model
	RoomID   uint   `json:"room_id" gorm:"not null"`
	UserID   int    `json:"user_id" gorm:"not null"`
	UserName string `json:"user_name" gorm:"size:50"`
	JoinTime int64  `json:"join_time" gorm:"not null"`
}

func CreateRoom(room *Room) error {
	return GetDB().Create(room).Error
}

func GetAllRooms() ([]Room, error) {
	var rooms []Room
	err := GetDB().Find(&rooms).Error
	return rooms, err
}

func GetRoomByID(id string) (*Room, error) {
	var room Room
	err := GetDB().First(&room, id).Error
	return &room, err
}

func DeleteRoomByID(id string) error {
	return GetDB().Delete(&Room{}, id).Error
}

func SetRoomEmptySince(id string, t time.Time) error {
	return GetDB().Model(&Room{}).Where("id = ?", id).Update("empty_since", t).Error
}

func ClearRoomEmptySince(id string) error {
	return GetDB().Model(&Room{}).Where("id = ?", id).Update("empty_since", nil).Error
}

// GetRoomUserCount 获取房间的用户数量
func GetRoomUserCount(roomID uint) (int, error) {
	var count int64
	err := GetDB().Table("room_users").Where("room_id = ?", roomID).Count(&count).Error
	return int(count), err
}

// AddUserToRoom 添加用户到房间
func AddUserToRoom(roomID uint, userID int, userName string) error {
	roomUser := &RoomUser{
		RoomID:   roomID,
		UserID:   userID,
		UserName: userName,
		JoinTime: time.Now().Unix(),
	}
	return GetDB().Create(roomUser).Error
}

// RemoveUserFromRoom 从房间移除用户
func RemoveUserFromRoom(roomID uint, userID int) error {
	return GetDB().Where("room_id = ? AND user_id = ?", roomID, userID).Delete(&RoomUser{}).Error
}

// GetRoomUsers 获取房间的所有用户
func GetRoomUsers(roomID uint) ([]RoomUser, error) {
	var users []RoomUser
	err := GetDB().Where("room_id = ?", roomID).Find(&users).Error
	return users, err
}
